﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BEELab
{
    public partial class UserManagement : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Admin"] == null || (bool)Session["Admin"] == false)
            {
                Response.Redirect("Main.aspx");
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (!IsPostBack)
            {
                return;
            }

            if (e.CommandName == "ChangePassword")
            {
                string token = BEELab.Logic.UserManagement.CreateToken(GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[1].Text);
                Response.Redirect("ResetPassword.aspx?Token=" + token);
            }
            else if (e.CommandName == "ChangeAdmin")
            {
                BEELab.Logic.UserManagement.SetAdmin(GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[1].Text, !BEELab.Logic.UserManagement.IsAdmin(GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[1].Text));
                GridView1.DataBind();
            }
            else if (e.CommandName == "Impersonate")
            {
                Session["UserEmail"] = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[1].Text;
                Session["UserID"] = BEELab.Logic.UserManagement.GetUserID(Session["UserEmail"].ToString());
                Session["Admin"] = BEELab.Logic.UserManagement.IsAdmin(Session["UserEmail"].ToString());
                Response.Redirect("Main.aspx");
            }
            else if (e.CommandName == "Delete")
            {
                int userID = BEELab.Logic.UserManagement.GetUserID(GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[1].Text);
                BEELab.Logic.UserManagement.DeleteUser(userID);
                if (userID == int.Parse(Session["UserID"].ToString()))
                {
                    Session["UserEmail"] = null;
                    Session["UserID"] = null;
                    Session["Admin"] = null;
                    Response.Redirect("Default.aspx");
                }
            }
        }
    }
}